<?php
/**
 * admin service file Created by PhpStorm.
 * User: yang
 * Date: 2020/06/11
 */

namespace App\Http\Service\Web;

use Common\Repository\ForumRepository;
use Common\Repository\UserRepository;
use Illuminate\Support\Facades\Hash;

class UserService
{
    /**
     * 获取个人信息
     * @param array $data
     * @return array
     */
    public function home($data = [])
    {
        if ($data['name']) {
            $where['where']['name'] = $data['name'];
        } elseif ($data['id']) {
            $where['where']['id'] = $data['id'];
        } else {
            $where['where']['id'] = web_user_info()['id'];
        }

        $user = UserRepository::getOne($where);

        return ['user' => $user];
    }

    /**
     * 获取登录者个人信息
     * @return array
     */
    public function getUser()
    {
        $user = web_user_info();

        return ['user' => $user];
    }

    /**
     * 个人设置
     * @param array $post_data
     * @return array|\Illuminate\Http\JsonResponse
     */
    public function setIng($post_data = [])
    {
        try {
            if ($post_data['password'] && $post_data['pass'] && $post_data['repass']) {
                if ($post_data['pass'] != $post_data['repass']) {
                    return hello_error('两次输入密码不一致！');
                }
                if ($post_data['password']) {
                    $old = UserRepository::findOne($post_data['id']);
                    // 对比原密码
                    if (!Hash::check($post_data['password'], $old['password'])) {
                        return hello_error('原密码不正确！');
                    }
                }
                $post_data['password'] = Hash::make($post_data['pass']);
                unset($post_data['repass']);
            }

            $result = UserRepository::editOne($post_data);

            if ($result) {
                return json_success('修改成功！');
            }

            return hello_error('修改失败！');
        } catch (\Exception $exception) {
            return hello_error('失败！', $exception->getMessage());
        }
    }

    /**
     * 用户中心获取帖子列表
     * @return array|\Illuminate\Http\JsonResponse
     */
    public function index()
    {
        try {
            $user = web_user_info();
            $arr_option['limit'] = 10;
            $arr_option['where'] = ['user_id' => $user['id']];
            $arr_option['withCount'] = ['get_comment'];
            $arr_option['field'] = ['id', 'title', 'views_num', 'created_at'];
            $result = ForumRepository::getList($arr_option);

            return $result;
        } catch (\Exception $exception) {
            return hello_error('失败！', $exception->getMessage());
        }
    }


}